package com.example.aliceapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivityController extends Activity {

	private static final int REQUEST_ENABLE_BT = 1;
	private ArrayList<String> addressList;
	private ListView listDevicesFound;
	private Button btnScanDevice;
	private TextView stateBluetooth;
	private BluetoothAdapter bluetoothAdapter;
	private BluetoothConnector bc;
	private boolean isConnected = false;

	private static final UUID myUUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");

	ArrayAdapter<String> btArrayAdapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		addressList = new ArrayList<String>();
		btnScanDevice = (Button) findViewById(R.id.scandevice);

		stateBluetooth = (TextView) findViewById(R.id.bluetoothstate);
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		listDevicesFound = (ListView) findViewById(R.id.devicesfound);
		btArrayAdapter = new ArrayAdapter<String>(MainActivityController.this,
				android.R.layout.simple_list_item_1);
		listDevicesFound.setAdapter(btArrayAdapter);

		CheckBlueToothState();

		btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
		listDevicesFound.setOnItemClickListener(new onListClickListener(this));

		registerReceiver(ActionFoundReceiver, new IntentFilter(
				BluetoothDevice.ACTION_FOUND));

		bc = BluetoothConnector.getInstance();
		if(isConnected){
			bc.stopSocket();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(ActionFoundReceiver);
	}

	private void CheckBlueToothState() {
		if (bluetoothAdapter == null) {
			stateBluetooth.setText("Bluetooth NOT support");
		} else {
			if (bluetoothAdapter.isEnabled()) {
				if (bluetoothAdapter.isDiscovering()) {
					stateBluetooth
							.setText("Bluetooth is currently in device discovery process.");
				} else {
					stateBluetooth.setText("Bluetooth is Enabled.");
					btnScanDevice.setEnabled(true);
				}
			} else {
				stateBluetooth.setText("Bluetooth is NOT Enabled!");
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}
		}
	}

	private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			btArrayAdapter.clear();
			bluetoothAdapter.startDiscovery();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQUEST_ENABLE_BT) {
			CheckBlueToothState();
		}
	}

	private class onListClickListener implements
			AdapterView.OnItemClickListener {

		private Activity a;

		public onListClickListener(Activity a) {
			this.a = a;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {
			Toast.makeText(MainActivityController.this, addressList.get(pos),
					Toast.LENGTH_SHORT).show();
			BluetoothDevice bDevice = bluetoothAdapter
					.getRemoteDevice(addressList.get(pos));
			try {
				bluetoothAdapter.cancelDiscovery();
				BluetoothSocket bs = bDevice
						.createRfcommSocketToServiceRecord(myUUID);
				bc.setSocket(bs);

				bs.connect();
				isConnected = true;

			} catch (IOException e) {
				e.printStackTrace();
			}
			Intent controlIntent = new Intent(MainActivityController.this,
					ButtonView.class);
			startActivity(controlIntent);
		}

	}

	private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				btArrayAdapter.add(device.getName() + "\n"
						+ device.getAddress());
				addressList.add(device.getAddress());
				btArrayAdapter.notifyDataSetChanged();
			}
		}
	};

}